package com.estore.network;
import com.estore.service.ProductService;
// 补充导入Product实体类（需确认包路径是否为com.estore.entity）
import com.estore.entity.Product;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
public class EStoreServer {
    private final ProductService productService = new ProductService();

    public static void main(String[] args) {
        new EStoreServer().startServer();
    }

    private void startServer() {
        // 绑定端口8888
        try (ServerSocket serverSocket = new ServerSocket(8888)) {
            System.out.println("服务器已启动，监听端口8888...");
            // 无限循环等待客户端连接
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端已连接：" + clientSocket.getInetAddress());
                // 处理客户端请求（可通过多线程优化，此处先单线程示例）
                handleClient(clientSocket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void handleClient(Socket clientSocket) {
        try (
                ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
                ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream())
        ) {
            // 1. 读取客户端请求
            String request = (String) ois.readObject();
            System.out.println("收到请求：" + request);

            // 2. 根据请求处理业务
            Object responseData = null;
            if ("GET_ALL_PRODUCTS".equals(request)) {
                // 补充泛型明确性
                List<Product> productList = productService.getAllProducts();
                responseData = productList;
            }
            // 补充：默认请求的处理分支
            else {
                responseData = "不支持的请求类型：" + request;
            }

            // 3. 回写数据给客户端
            oos.writeObject(responseData);
            oos.flush();
            System.out.println("请求处理完成，已返回数据");

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
